<template>
	<div class="addVisiting-container">
		<van-form label-align="left" @submit="onSubmit" ref="addCustomerForm">
			<van-cell-group>
				<van-field name="radio" label="客户类型">
					<template #input>
						<van-radio-group v-model="selectCustomerType" direction="horizontal">
							<van-radio v-for="item in customerTypeColumns" :key="item.value" :name="item.value">{{
									item.text
								}}
							</van-radio>
						</van-radio-group>
					</template>
				</van-field>
				<!--        <van-field-->
				<!--          v-model="customerName"-->
				<!--          name="客户名称"-->
				<!--          label="客户名称"-->
				<!--          required-->
				<!--          placeholder="客户名称"-->
				<!--          :rules="[{ required: true, message: '请填写客户名称' }]"-->
				<!--        />-->
				<van-field
					v-model="customerName"
					name="客户名称"
					label="客户名称"
					required
					placeholder="客户名称"
					:disabled="!!customerId"
					@input="inputCustomerName"
					:rules="[{ required: true, message: '请填写客户名称' }]"
				/>
				<van-popup v-model:show="showCustomerListPicker" position="bottom">
					<van-picker
						:columns="customerList"
						:columns-field-names="customFieldName"
						@confirm="onConfirmCustomerList"
						@cancel="showCustomerListPicker = false"
					/>
				</van-popup>
				
				<van-field
					v-model="customerStatus.text"
					is-link
					readonly
					name="picker"
					label="客户状态"
					placeholder="点击选择客户状态"
					@click="showCustomerStatusPicker = true"
				/>
				<van-popup v-model:show="showCustomerStatusPicker" position="bottom">
					<van-picker
						:columns="customerStatusColumns"
						@confirm="onConfirmCustomerStatus"
						@cancel="showCustomerStatusPicker = false"
					/>
				</van-popup>
				<van-field
					v-model="customerSource.text"
					is-link
					readonly
					name="picker"
					label="客户来源"
					placeholder="点击选择客户来源"
					@click="showCustomerSourcePicker = true"
				/>
				<van-popup v-model:show="showCustomerSourcePicker" position="bottom">
					<van-picker
						:columns="customerSourceColumns"
						@confirm="onConfirmCustomerSource"
						@cancel="showCustomerSourcePicker = false"
					/>
				</van-popup>
				<van-field
					v-model="customerStar.text"
					is-link
					readonly
					name="picker"
					label="客户星级"
					placeholder="点击选择客户星级"
					@click="showCustomerStarPicker = true"
				/>
				<van-popup v-model:show="showCustomerStarPicker" position="bottom">
					<van-picker
						:columns="customerStarColumns"
						@confirm="onConfirmCustomerStar"
						@cancel="showCustomerStarPicker = false"
					/>
				</van-popup>
				<van-field
					v-model="areaResult"
					is-link
					readonly
					name="area"
					label="所在地区"
					placeholder="点击选择省市区"
					@click="showArea = true"
				/>
				<van-popup v-model:show="showArea" position="bottom">
					<van-area :area-list="areaList" @confirm="onConfirmArea" @cancel="showArea = false"/>
				</van-popup>
				
				<van-field
					v-model="street"
					name="所在街道"
					label="所在街道"
					right-icon="location-o"
					placeholder="所在街道"
					@click-right-icon="getLocation"
				/>
				<van-field
					v-model="createTime"
					is-link
					readonly
					name="datePicker"
					label="创建日期"
					disabled
				/>
				<van-field v-model="linkman" name="联系人" label="联系人" placeholder="联系人" required
				           :rules="[{ required: true, message: '请填写联系人' }]"/>
				<van-field v-model="linkmanPhone" name="联系电话" label="联系电话" placeholder="联系电话" required
				           :rules="[{ required: true, message: '请填写联系电话' }]"/>
				<van-field v-model="linkmanEmail" name="邮箱" label="邮箱" placeholder="邮箱"/>
				<van-field name="uploader" label="文件上传">
					<template #input>
						<van-uploader v-model="customerFile" :after-read="afterRead" :before-delete="deleteCustomerFile"  :preview-options="{closeable:'true'}"/>
					</template>
				</van-field>
				<van-field v-model="remark" type="textarea" name="备注" label="备注" placeholder="备注"/>
			</van-cell-group>
			<div v-if="customerId">
				<div style="margin: 0 15px; font-size: 14px">企业信息</div>
				<van-field
					v-model="customerInfo.customerName"
					name="企业名称"
					label="企业名称"
					placeholder="企业名称"
					disabled
				/>
				<van-field
					v-model="customerInfo.creditCode"
					name="统一社会信用代码"
					label="统一社会信用代码"
					placeholder="统一社会信用代码"
					disabled
				/>
				<van-field
					v-model="customerInfo.orgNo"
					name="组织机构代码"
					label="组织机构代码"
					placeholder="组织机构代码"
					disabled
				/>
				<van-field
					v-model="customerInfo.operName"
					name="法人代表"
					label="法人代表"
					placeholder="法人代表"
					disabled
				/>
				<van-field
					v-model="customerInfo.customerNo"
					name="工商注册号"
					label="工商注册号"
					placeholder="工商注册号"
					disabled
				/>
				<van-field
					v-model="customerInfo.termStart"
					name="成立日期"
					label="成立日期"
					placeholder="成立日期"
					disabled
				/>
				<van-field
					v-model="customerInfo.checkDate"
					name="核准日期"
					label="核准日期"
					placeholder="核准日期"
					disabled
				/>
				<van-field
					v-model="customerInfo.customerStatus"
					name="经营状态"
					label="经营状态"
					placeholder="经营状态"
					disabled
				/>
				<van-field
					v-model="customerInfo.registCapi"
					name="注册资本"
					label="注册资本"
					placeholder="注册资本"
					disabled
				/>
				<van-field
					v-model="customerInfo.econKind"
					name="企业类型"
					label="企业类型"
					placeholder="企业类型"
					disabled
				/>
				<van-field
					v-model="customerInfo.belongOrg"
					name="注册地址"
					label="注册地址"
					placeholder="注册地址"
					disabled
				/>
				<van-field
					v-model="customerInfo.startDate"
					name="营业期限"
					label="营业期限"
					placeholder="营业期限"
					disabled
				>
					<template v-slot:input>
						<div style="color: #c8c9cc">{{ customerInfo.startDate }}至{{ customerInfo.termEnd || '无限' }}</div>
					</template>
				</van-field>
				<van-field
					v-model="customerInfo.scope"
					name="经验范围"
					label="经验范围"
					placeholder="经验范围"
					type="textarea"
					rows="10"
					disabled
				/>
			</div>
			
			<div style="margin: 16px">
				<van-button round block type="primary" native-type="submit"> 保存</van-button>
			</div>
		</van-form>
	</div>
</template>

<script>
import {onMounted, reactive, ref, toRefs} from 'vue'
import {areaList} from '@/utils/area.js'
import {getBizDictionary, getDictionary} from '@/api/dictionary.js'
import {
	customerStorage,
	detailInformationByCustomerId,
	getCustomerBaseInfo,
	getCustomerInfo,
	customerUpdate
} from "@/api/customer.js";
import {useRouter, useRoute} from "vue-router";
import request from "@/utils/request.js";
import {Toast} from "vant";
import {formatTotalDate} from "@/utils/index.js";

export default {
	setup() {
		const router = useRouter()
		const route = useRoute()
		const addCustomerForm = ref(null)
		const state = reactive({
			customerId: '',
			selectCustomerType: '',
			customerTypeColumns: [],
			customerName: '',
			customerList: [],
			customFieldName: {text: 'Name', value: 'Name'},
			showCustomerListPicker: false,
			customerInfo: {},
			customerBaseInfo: {},
			customerStatus: {
				text: '',
				value: ''
			},
			showCustomerStatusPicker: false,
			customerStatusColumns: [],
			customerSource: {},
			showCustomerSourcePicker: false,
			customerSourceColumns: [],
			customerStar: {},
			showCustomerStarPicker: false,
			customerStarColumns: [],
			areaResult: '',
			areaCode: [],
			showArea: false,
			street: '',
			createTime: '',
			linkman: '',
			linkmanId: '',
			linkmanPhone: '',
			linkmanEmail: '',
			customerFile: [],
			customerUploadFile: [],
			remark: ''
		})
		
		onMounted(async () => {
			initDictionary('customer_type')
			initDictionary('customer_state')
			initBizDictionary('crm_customer_source')
			initBizDictionary('crm_customer_level')
			
			state.createTime = formatTotalDate(new Date())
			console.log(router)
			console.log("route:::", route)
			console.log("route:::", route.query)
			if (route.query.id) {
				document.title='编辑客户'
				state.customerId = route.query.id
				setTimeout(() => {
					getCustomerBaseInfoDetail()
				})
			}
		})
		
		const initDictionary = (code) => {
			getDictionary({code}).then((res) => {
				const newDic = transOption(res)
				console.log('newDic::::', newDic)
				if (code === 'customer_type') {
					state.customerTypeColumns = newDic
					state.selectCustomerType = newDic[0].value
				} else if (code === 'customer_state') {
					state.customerStatusColumns = newDic
				}
			})
		}
		
		const initBizDictionary = (code) => {
			getBizDictionary({code}).then((res) => {
				const newDic = transOption(res)
				console.log('bizCode:::', res)
				if (code === 'crm_customer_level') {
					state.customerStarColumns = newDic
				} else if (code === 'crm_customer_source') {
					state.customerSourceColumns = newDic
				}
			})
		}
		
		const transOption = (data) => {
			const newDate = []
			data.map((item) => {
				const obj = {
					text: item.dictValue,
					value: item.dictKey
				}
				newDate.push(obj)
			})
			return newDate
		}
		
		const getCustomerBaseInfoDetail = () => {
			getCustomerBaseInfo(state.customerId).then(res => {
				state.customerBaseInfo = res
				if (res.customerType) {
					let customerType  = state.customerTypeColumns.find(item => item.value === res.customerType)
					console.log("customerType;::", customerType)
					state.selectCustomerType = customerType.value
				}
				if (res.customerState) {
					state.customerStatus = state.customerStatusColumns.find(item => item.value === res.customerState)
				}
				if (res.customerSource) {
					state.customerSource = state.customerSourceColumns.find(item => item.value === res.customerSource)
				}
				if (res.customerLevel) {
					state.customerStar = state.customerStarColumns.find(item => item.value === res.customerLevel)
				}
				state.customerName = res.name
				state.areaResult = res.address
				state.street = res.detailAddress
				state.createTime = res.createTime
				state.linkman = res.contactsReq?.name
				state.linkmanId = res.contactsReq?.id
				state.linkmanPhone = res.contactsReq?.phoneNumber
				state.linkmanEmail = res.contactsReq?.email
				state.remark = res.remark
				state.customerInfo = res.customerInformationDTO
				if (res?.enclosureList?.length) {
					res.enclosureList.forEach(item => {
						state.customerFile.push({
							url: item.value
						})
					})
					state.customerUploadFile = res.enclosureList
				}
			})
		}
		
		const getCustomerDetail = () => {
			detailInformationByCustomerId(state.customerId).then(res => {
				console.log("..........", res)
				state.customerInfo = res
			})
		}
		
		const inputCustomerName = (value) => {
			console.log("::::", value.data)
			getCustomerInfo(value.data).then(res => {
				console.log("....", res)
				if (res.length) {
					state.customerList = res
					state.showCustomerListPicker = true
				}
			})
		}
		
		// const blurCustomerName = () => {
		// 	if (state.customerList.length) {
		// 		state.showCustomerListPicker = true
		// 	}
		// }
		
		const onConfirmCustomerList = (value) => {
			state.customerName = value.Name
			state.showCustomerListPicker = false
		}
		
		
		const onConfirmCustomerStatus = (value) => {
			state.customerStatus = value
			state.showCustomerStatusPicker = false
		}
		
		const onConfirmCustomerSource = (value) => {
			state.customerSource = value
			state.showCustomerSourcePicker = false
		}
		
		const onConfirmCustomerStar = (value) => {
			state.customerStar = value
			state.showCustomerStarPicker = false
		}
		
		const onConfirmArea = (value) => {
			console.log('选择省市区', value)
			let city = ''
			let cityCode = []
			value.forEach((item) => {
				city += item.name
				cityCode.push(item.code)
			})
			state.areaResult = city
			state.areaCode = cityCode
			state.showArea = false
			console.log(state.areaResult)
			console.log(state.areaCode)
		}
		
		const getLocation = () => {
			console.log('点击定位')
		}
		
		const deleteCustomerFile = (file, indexData) => {
			state.customerFile.splice(indexData.index, 1)
			state.customerUploadFile.splice(indexData.index, 1)
		}
		
		const afterRead = (file) => {
			// 此时可以自行将文件上传至服务器
			console.log(file)
			console.log('customerFile:::', state.customerFile)
			const formData = new FormData();
			formData.append('file', file.file);
			
			// 示例使用 axios 进行文件上传
			uploadFile(formData);
		}
		
		const uploadFile = (formData) => {
			// 使用你的上传接口地址替换以下 URL
			const url = 'web-service/oss/endpoint/put-file';
			// 这里使用 axios 作为请求示例
			request.post(url, formData, {
				headers: {
					'Content-Type': 'multipart/form-data',
				},
				onUploadProgress: progressEvent => {
					// 这里可以获取上传进度
					console.log(progressEvent);
				},
			})
				.then(response => {
					// 上传成功处理
					console.log("response::::", response);
					console.log("followUpFile::::", state.customerFile);
					state.customerUploadFile.push({
						label: response.originalName,
						value: response.link,
					})
				})
				.catch(error => {
					// 上传失败处理
					console.error(error);
				});
		}
		
		const onSubmit = () => {
			addCustomerForm.value.validate().then(() => {
				const {realName, deptName, id, deptId, phone} = JSON.parse(localStorage.getItem('userInfo'))
				
				let params = {
					customerType: state.selectCustomerType,
					name: state.customerName,
					ownerUserId: id,
					ownerUser: realName,
					ownerDeptId: deptId,
					ownerDeptName: deptName,
					ownerPhoneNumber: phone,
					customerState: state.customerStatus.value,
					customerSource: state.customerSource.value,
					customerLevel: state.customerStar.value,
					address: state.areaResult,
					addressCode: state.areaCode.join(','),
					addressCodeList: state.areaCode,
					detailAddress: state.street,
					enclosureList: state.customerUploadFile,
					remark: state.remark,
					contactsReq: {
						name: state.linkman,
						id: state.linkmanId,
						phoneNumber: state.linkmanPhone,
						email: state.linkmanEmail
					},
				}
				console.log('提交', params)
				if (state.customerId) {
					params.id = state.customerId
					customerUpdate(params).then((res) => {
						console.log('res::::', res)
						Toast.success('编辑客户成功！')
						setTimeout(() => {
							router.back()
						}, 500)
					})
				} else {
					customerStorage(params).then((res) => {
						console.log('res::::', res)
						Toast.success('新建客户成功！')
						setTimeout(() => {
							router.back()
						}, 500)
					})
				}
			})
		}
		
		return {
			areaList,
			addCustomerForm,
			...toRefs(state),
			onSubmit,
			inputCustomerName,
			onConfirmCustomerList,
			getLocation,
			onConfirmArea,
			afterRead,
			deleteCustomerFile,
			onConfirmCustomerStatus,
			onConfirmCustomerSource,
			onConfirmCustomerStar
		}
	}
}
</script>

<style scoped lang="less">
.addVisiting-container {
	.addVisiting-save {
		display: flex;
		justify-content: flex-end;
		margin: 20px;
	}
}
</style>
